# -*- coding: utf-8 -*-

import socketio
import eventlet
import threading
from login import *
import os
from flask_wtf.csrf import CSRFProtect
from admin_user import *
from flask_login import login_user, login_required
from flask_login import LoginManager, current_user
from flask_login import logout_user
from collections import deque
import json
from config import *
from calprofit import *
from utility import *
from sellprice import *


sio = socketio.Server()
app = get_app()
db = SQLAlchemy(app)

login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_view = 'login'
login_manager.init_app(app=app)
csrf = CSRFProtect()
csrf.init_app(app)

price_info = {}
price_info_queue = deque(maxlen=14)
last_datetime = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
last_time = datetime.now().strftime('%H:%M:%S')

@login_manager.user_loader
def load_user(user_id):
    return User.get(user_id)


@app.route("/main")
@login_required
def index_sb():
    """Serve the client-side application."""
    return render_template('index_sb.html')

@app.route("/m")
#@login_required
def index():
    """Serve the client-side application."""
    host_url = request.host_url
    return render_template('index.html', **locals())

@app.route("/s")
#@login_required
def sellprice_page():
    """Serve the client-side application."""
    host_url = request.host_url
    return render_template('sellprice.html', **locals())

@app.route("/coinone_btc_sell_cal",methods=['POST'])
def coinone_btc_sell_cal():
    benjin = Decimal(request.form["benjin"])
    usd2cny = Decimal(request.form["usd_huilv"])
    coinnum = Decimal(request.form["coinnum"])
    obj = coinone_btc_sell(coinnum,benjin,price_info)
    return json.dumps(obj, default=json_encode_custom)


@app.route("/charts",methods=['GET'])
@login_required
def charts():

    """Serve the client-side application."""
    return render_template('flot.html')

@sio.on('connect')
def connect(sid, environ):
    print('connect ', sid)

@sio.on('chat message')
def message(sid, data):
    try:
        tmp = data.split(",")
        benjin = Decimal(tmp[0])
        usd2cny = Decimal(tmp[1])
        coinnum = Decimal(tmp[2])
        #str = cal_benefit(Decimal(benjin))
        profit = cal_profit_info(benjin, price_info , usd2cny ,coinnum)
        profit["last_datetime"] = last_datetime
        str = json.dumps(profit , default=json_encode_custom)
        sio.emit("chat message", str, room=sid)
    except Exception as exp:
        print exp
        print "显示输出错误"
        noneJson = {}
        sio.emit("chat message", json.dumps(noneJson, default=json_encode_custom), room=sid)



def callback_ack(data):
    print data




@sio.on('all_price')
def message(sid, data):
    try:
        queue_arr = []
        for it in price_info_queue: queue_arr.append(it)
        sio.emit("all_price", json.dumps(queue_arr), room=sid )
    except:
        sio.emit("all_price", "error", room=sid)


@sio.on('disconnect')
def disconnect(sid):
    print('disconnect ', sid)

@app.route('/login',methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        user_name = request.form.get('username', None)
        password = request.form.get('password', None)
        remember_me = request.form.get('remember_me', False)
        user = User.getUserByName(user_name)
        if user.verify_password(password):
            login_user(user,remember=remember_me)
            return redirect(request.args.get('next') or "main")
    return render_template('login2.html', title="Sign In", form=form)

@app.route('/loginout',methods=['GET', 'POST'])
def loginout():
    logout_user()
    return redirect("main")



def run_getinfo():
    global price_info
    global last_datetime
    global price_info_queue
    global last_time
    while (1):
        try:
            price_info = get_info()

            # price_info_obj = {}
            # price_info_obj["stamp"] = [last_time , round(float(price_info[stamp_btc2usd_price] * get_usd2cny()),2)]
            # price_info_obj["lhang"] = [last_time, round(float(price_info[lh_btc2cny_price]),2)]
            # price_info_obj["coinone"] = [last_time, round(float(price_info[coinone_btc2kwr_price]*get_krw2cny()),2)]
            # #price_info_obj["btce"] = [last_time, round(float(price_info[btce_btc2usd]*get_usd2cny()),2)]
            # price_info_queue.append(price_info_obj)

        except:
            print "数据获取异常"
        last_datetime = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        last_time = datetime.now().strftime('%H:%M:%S')
        time.sleep(1)



if __name__ == '__main__':
    # wrap Flask application with socketio's middleware
    app = socketio.Middleware(sio, app)
    t = threading.Thread(target=run_getinfo, args=())
    t.start()
    # deploy as an eventlet WSGI server
    eventlet.wsgi.server(eventlet.listen(('', 8001)), app)

